package com.ncepu.clubmanagement.filter;

import com.alibaba.fastjson.JSONObject;
import com.ncepu.clubmanagement.pojo.Result;
import com.ncepu.clubmanagement.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
public class LoginFilter implements Filter {

    private JwtUtils jwtUtils;

    public LoginFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        // 1.类型转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        // 2.获取并判定url是否包含login
        String url = req.getRequestURL().toString();

        String method = req.getMethod();
        // 对于预检请求，直接放行 (CORS跨域请求的配置)
        if ("OPTIONS".equals(method)) {
            log.info("LoginFilter handling preflight request for URL: {}", url);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        if (url.contains("/login") || url.contains("/register") || url.contains("/university")) {
            log.info("LoginFilter放行{}", url);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 3.获取令牌(接口文档明确规定)
        String jwt = req.getHeader("token");
        // 4.令牌检验是否为空
        if(!StringUtils.hasLength(jwt)){  // 空
            log.info("LoginFilter令牌为空");
            // 注意：没有RestController修饰，返回json格式需要手动操作
            // 手动转换(使用fastjson)
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);

            // CORS配置
            resp.setHeader("Access-Control-Allow-Origin", "*"); // 或者特定的域名
            resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            resp.setHeader("Access-Control-Allow-Headers", "*");
            resp.setHeader("Access-Control-Allow-Credentials", "true");


            resp.getWriter().write(jsonString);
            return;

        }
        // 5.令牌校验
        try{
            jwtUtils.parseJWT(jwt);
        }catch (Exception e){
            log.info("LoginFilter令牌校验失败");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);

            // CORS配置
            resp.setHeader("Access-Control-Allow-Origin", "*"); // 或者特定的域名
            resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            resp.setHeader("Access-Control-Allow-Headers", "*");
            resp.setHeader("Access-Control-Allow-Credentials", "true");



            resp.getWriter().write(jsonString);
            return;
        }

        // 6.放行
        log.info("LoginFilter放行{}", url);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
